""" 编写日志相关功能 """
import os

from django.http import HttpResponse, JsonResponse
import time
from dwebsocket.decorators import accept_websocket

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


@accept_websocket
def read_log(request):
    if not request.is_websocket():
        # 判断是不是websocket连接
        try:
            message = request.GET['message']
            # 如果是普通的http方法
            return HttpResponse(message)
        except:
            return JsonResponse({'code': '1', 'msg': "任务失败"})
    else:
        for message in request.websocket:
            message = message.decode('utf-8')
            # 接收前端发来的数据
            if message == 'system_log':
                log_dir = os.path.join(BASE_DIR, 'logs/system.log')
            elif message == 'userManage_log':
                log_dir = os.path.join(BASE_DIR, 'logs/user_management.log')
            else:
                request.websocket.send('sorry!'.encode('utf-8'))

            try:
                # 读日志
                with open(log_dir, 'r') as f:
                    while True:
                        line = f.readline()
                        if line and line != '\n':  # 空行不打印
                            request.websocket.send(line.encode('utf-8'))
                        else:
                            time.sleep(1)
                    f.close()
            except FileNotFoundError:
                print("FileNotFoundError")
            finally:
                pass
